<template>
  <div class="history-container">
    <a-page-header title="My History" sub-title="View your recently viewed products" />

    <div class="history-actions">
      <div class="action-left">
        <a-select v-model:value="timeRange" style="width: 150px" placeholder="Time Range">
          <a-select-option value="all">All Time</a-select-option>
          <a-select-option value="today">Today</a-select-option>
          <a-select-option value="yesterday">Yesterday</a-select-option>
          <a-select-option value="week">Week</a-select-option>
          <a-select-option value="month">Month</a-select-option>
        </a-select>
      </div>
      <div class="action-right">
        <a-button type="primary" danger @click="clearAllHistory" class="clear-btn">
          <DeleteOutlined />
          Clear History
        </a-button>
      </div>
    </div>

    <a-spin :spinning="loading">
      <div v-if="!hasHistory" class="empty-state">
        <a-empty description="No browsing history" />
        <a-button type="primary" @click="goToProducts">Go to products</a-button>
      </div>

      <a-timeline v-else class="history-timeline">
        <div v-for="group in historyByDate" :key="group.date" class="timeline-section">
          <div class="timeline-date-wrapper">
            <div class="timeline-date">
              <DateFormatter :value="group.date" format="MM/DD/YYYY" />
            </div>
          </div>
          <a-timeline-item class="timeline-item">
            <template #dot>
              <ClockCircleOutlined style="font-size: 16px;" />
            </template>

            <div class="date-group">
              <a-list :grid="{ gutter: 24, xs: 1, sm: 2, md: 2, lg: 3, xl: 3, xxl: 4 }" :data-source="group.items">
                <template #renderItem="{ item }">
                  <a-list-item>
                    <a-card hoverable @click.stop="viewProductDetail(item)">
                      <template #cover>
                        <img
                          :src="item.image"
                          :onerror="'this.onerror=null; this.src=\'https://via.placeholder.com/300x300?text=No+Image\';'"
                          :alt="item.name"
                          style="height: 400px; object-fit: cover;"
                        />
                      </template>
                      <a-card-meta :title="item.name">
                        <template #description>
                          <div class="card-info">
                            <div class="product-price">{{ currency.unit }}{{ formatPrice(item.price) }}</div>
                            <div class="view-time-wrapper">
                              <div class="view-time">
                                <ClockCircleOutlined class="time-icon" />
                                <DateFormatter :value="item.viewedDate" format="HH:mm:ss" />
                              </div>
                            </div>
                          </div>
                        </template>
                      </a-card-meta>
                      <div class="product-actions">
                        <a-button type="primary" shape="circle" size="middle" @click.stop="addToCart(item)">
                          <template #icon>
                            <ShoppingCartOutlined />
                          </template>
                        </a-button>
                        <a-button danger shape="circle" size="middle" :loading="loadingStates[String(item.id)]"
                          :disabled="pendingRequests.has(`favorite_${item.id}`)"
                          @click="(e: Event) => handleAddFavorite(item, e)">
                          <template #icon>
                            <HeartFilled v-if="isInFavorites(item.id)" />
                            <HeartOutlined v-else />
                          </template>
                        </a-button>
                      </div>
                    </a-card>
                  </a-list-item>
                </template>
              </a-list>
            </div>
          </a-timeline-item>
        </div>
      </a-timeline>
    </a-spin>
  </div>

  <a-modal v-model:open="open" width="1200px" title="Product Details" @close="updateFavoriteStatuses" :footer="null">
    <ProductDetail.default v-if="open && goodId" :goodId="goodId" @buy="handleBuy" />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { message, Modal } from 'ant-design-vue';
import { useCurrencyStore } from '@/store';
import { ClockCircleOutlined, ShoppingCartOutlined, HeartOutlined, HeartFilled, DeleteOutlined } from '@ant-design/icons-vue';
import { addCollect, deleteCollect } from '@/api/user';
import * as ProductDetail from '@/components/ProductDetail.vue';
import DateFormatter from '@/components/common/DateFormatter.vue';
import { getBrowsingHistory, clearBrowsingHistory } from '@/utils/cache';
import { isInFavorites, addToFavorites as addToFavoritesLocal, removeFromFavorites as removeFromFavoritesLocal, BrowsingHistoryAdapter } from '@/utils/cache';

const open = ref<boolean>(false);
const router = useRouter();
const { proxy }: any = getCurrentInstance();
const currencyStore = useCurrencyStore();
const currency = computed(() => currencyStore.currentCurrency);
const timeRange = ref('all');

// 浏览历史的适配器类型定义，添加类型提示以解决一些linter错误
interface BrowsingHistoryItem {
  id: string | number;
  goods_id: string | number;
  name: string;
  price: string | number;
  image: string;
  images: string[];
  viewedDate: string;
  date: string;
  url: string;
}

// 加载状态
const loadingStates: Record<string | number, boolean> = reactive({});
const loading = ref(false);

// 用于跟踪已发送请求的集合，避免重复请求
const pendingRequests = reactive(new Set<string>());

// 从本地存储加载浏览历史
const browsingHistory = ref<BrowsingHistoryItem[]>([]);

// 修改goodId类型为string，允许null
const goodId = ref<string | null>(null);

// 加载浏览历史数据
const loadBrowsingHistory = () => {
  browsingHistory.value = BrowsingHistoryAdapter.getAll();
  console.log('浏览历史:', browsingHistory.value);
};

// 货币转换辅助函数
const formatPrice = (price: number | string): string => {
  try {
    // 使用全局代理中的货币转换方法
    if (proxy && proxy.$ConvertPrice) {
      return proxy.$ConvertPrice(price, false, false);
    }

    // 备用转换逻辑
    const numPrice = Number(price);
    if (isNaN(numPrice)) return '0';
    const rate = currency.value.rate || 1;
    return (numPrice * rate).toFixed(2);
  } catch (error) {
    console.error('Failed to convert price:', error);
    return '0';
  }
};

// 按日期分组的历史记录
const historyByDate = computed(() => {
  return BrowsingHistoryAdapter.getByDateGroups(timeRange.value);
});

// 初始化加载数据
onMounted(() => {
  loading.value = true;
  // 从本地存储加载浏览历史
  loadBrowsingHistory();
  // 模拟加载延迟
  setTimeout(() => {
    loading.value = false;
  }, 500);
});

// 添加一个计算属性来检查是否有数据
const hasHistory = computed(() => {
  return historyByDate.value.length > 0;
});

// 查看商品详情
const viewProductDetail = (item: BrowsingHistoryItem) => {
  open.value = true;
  goodId.value = String(item.id);
};

// 处理加入购物车事件
const handleAddCart = (item: BrowsingHistoryItem, e: Event) => {
  e.preventDefault();
  e.stopPropagation();
  addToCart(item);
};

// 添加到购物车
const addToCart = (item: BrowsingHistoryItem) => {
  open.value = true;
  goodId.value = String(item.id); // 将数字ID转换为字符串
  // message.success(`已将 ${item.name} 加入购物车`);
};

// 处理添加收藏事件
const handleAddFavorite = (item: BrowsingHistoryItem, e: Event) => {
  e.preventDefault();
  e.stopPropagation();

  if (pendingRequests.has(`favorite_${item.id}`) || loadingStates[String(item.id)]) {
    return;
  }

  // 根据当前收藏状态决定是添加还是取消收藏
  const isFavorited = isInFavorites(item.id);
  if (isFavorited) {
    removeFavorite(item);
  } else {
    addToFavorites(item);
  }
};

// 添加到收藏
const addToFavorites = async (item: BrowsingHistoryItem) => {
  // 防止重复请求 - 使用商品ID作为唯一标识
  const requestKey = `favorite_${item.id}`;
  const itemId = String(item.id);

  // 记录此次请求并设置加载状态
  pendingRequests.add(requestKey);
  loadingStates[itemId] = true;

  try {
    const res = await addCollect({
      goods_id: item.id
    });

    // 统一在这里处理响应，无论成功还是失败
    if (res.code === 200) {
      message.success(`${item.name} has been added to favorites`);
      // 更新本地缓存
      addToFavoritesLocal(item);
    } else {
      // 接口返回了错误码，但不是网络错误，而是业务错误
      // 直接使用返回的错误信息
      const errorMsg = res.msg || (res.response?.data?.msg);
      message.error(errorMsg);
    }
  } catch (error: any) {
    // 这个分支只处理网络错误、超时等异常情况
    // 避免显示重复错误，只在控制台记录，不进行UI提示
    // 除非确定是网络错误而不是业务错误
    if (!error.response || error.response.status >= 500) {
      message.error('Network error, please try again later');
    }
  } finally {
    // 延迟清除请求状态，确保UI有足够时间响应
    setTimeout(() => {
      pendingRequests.delete(requestKey);
      loadingStates[itemId] = false;
    }, 1000); // 延长到1秒，确保完全防止重复点击
  }
};

// 从收藏中移除
const removeFavorite = async (item: BrowsingHistoryItem) => {
  // 防止重复请求 - 使用商品ID作为唯一标识
  const requestKey = `favorite_${item.id}`;
  const itemId = String(item.id);

  // 记录此次请求并设置加载状态
  pendingRequests.add(requestKey);
  loadingStates[itemId] = true;

  try {
    const res = await deleteCollect({
      goods_id: item.id
    });

    if (res.code === 200) {
      message.success(`${item.name} has been removed from favorites`);
      // 更新本地缓存
      removeFromFavoritesLocal(item.id);
    } else {
      const errorMsg = res.msg || (res.response?.data?.msg);
      message.error(errorMsg || 'Failed to remove from favorites');
    }
  } catch (error: any) {
    console.error('Failed to remove from favorites:', error);
    if (!error.response || error.response.status >= 500) {
      message.error('Network error, please try again later');
    }
  } finally {
    setTimeout(() => {
      pendingRequests.delete(requestKey);
      loadingStates[itemId] = false;
    }, 1000);
  }
};

// 清空浏览记录
const clearAllHistory = () => {
  Modal.confirm({
    title: 'Confirm clear',
    content: 'Are you sure you want to clear all browsing history? This action cannot be restored.',
    okText: 'Confirm',
    cancelText: 'Cancel',
    onOk: () => {
      BrowsingHistoryAdapter.clear(); // 使用适配器清空本地存储
      browsingHistory.value = []; // 清空当前页面显示的数据
      message.success('Browsing history has been cleared');
    }
  });
};

// 跳转到商品页面
const goToProducts = () => {
  router.push('/products');
};

const handleBuy = (product: any) => {
  console.log('Buy product:', product);
  message.success('The product has been successfully added to the cart');
  open.value = false;
};

// 更新浏览记录中商品的收藏状态
const updateFavoriteStatuses = () => {
  // 由于浏览记录中的商品可能在详情页被收藏/取消收藏
  // 这里需要重新加载浏览历史后重新渲染，以确保显示正确的收藏状态
  loadBrowsingHistory();
};

</script>

<style scoped>
.history-container {
  padding: 0;
  background: #fff;
}

.history-actions {
  margin: 16px 0;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-left {
  display: flex;
  align-items: center;
}

.action-right {
  display: flex;
  align-items: center;
}

.clear-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

/* 时间轴样式 */
:deep(.ant-timeline) {
  padding: 0 16px;

  .ant-timeline-item-head {
    background: #000;
    border-color: #000;

    .anticon {
      color: #fff;
    }
  }

  .ant-timeline-item-tail {
    border-left-color: #000;
  }
}

.date-group {
  margin-bottom: 32px;

  .date-title {
    color: #000;
    font-size: 18px;
    font-weight: 500;
    margin-bottom: 16px;
  }
}

/* 商品卡片样式 */
:deep(.ant-card) {
  border: 1px solid #eee;
  transition: all 0.3s;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .ant-card-cover {
    img {
      height: 200px;
      object-fit: cover;
      transition: all 0.3s;
    }
  }

  .ant-card-meta {
    margin: 16px 0;

    .ant-card-meta-title {
      color: #000;
      font-size: 16px;
      margin-bottom: 8px;
    }
  }
}

.card-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.product-price {
  color: #ff4d4f;
  font-size: 16px;
  font-weight: 600;
}

.view-time-wrapper {
  margin-top: 8px;
  background-color: #f8f8f8;
  padding: 5px 8px;
  border-radius: 4px;
  display: inline-block;
}

.view-time {
  color: #666;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.time-icon {
  font-size: 13px;
  color: #000;
}

.product-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

/* 空状态样式 */
.empty-state {
  padding: 48px 0;
  text-align: center;

  :deep(.ant-empty-description) {
    color: #666;
  }

  .ant-btn {
    margin-top: 16px;
  }
}

/* 加载状态样式 */
:deep(.ant-spin) {
  .ant-spin-dot-item {
    background-color: #000;
  }

  .ant-spin-text {
    color: #000;
  }
}

/* 更进一步优化时间轴样式 */
.history-timeline {
  margin-left: 100px;
  padding-left: 20px;
  position: relative;
}

.timeline-section {
  position: relative;
  margin-bottom: 40px;
}

.timeline-date-wrapper {
  position: absolute;
  left: -120px;
  top: 0;
  width: 110px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  z-index: 20;
}

.timeline-date {
  background-color: #000;
  color: #fff;
  padding: 6px 12px;
  border-radius: 4px;
  font-weight: bold;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 10;
  min-width: 100px;
  text-align: center;
  display: inline-block;
}

.timeline-date :deep(span) {
  color: #fff !important;
  font-weight: bold;
}

/* 强化时间轴线条和节点样式 */
:deep(.ant-timeline-item-tail) {
  border-left: 2px solid #000;
}

:deep(.ant-timeline-item-head) {
  background-color: #000 !important;
  border-color: #000 !important;
}

:deep(.ant-timeline-item-content) {
  padding-bottom: 20px;
}

/* 去掉内部日期标题 */
.date-title {
  display: none;
}
</style>
